package org.footballmanager.pandafootball.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.configure.AmqpConfig;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.domain.FootSociaty;
import org.footballmanager.pandafootball.system.domain.FootSociatyInfo;
import org.footballmanager.pandafootball.system.domain.FootUser;
import org.footballmanager.pandafootball.system.domain.enums.ZDZW;
import org.footballmanager.pandafootball.system.form.impl.FootSociatyInfoSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootSociatyInfoMapper;
import org.footballmanager.pandafootball.system.service.FootSociatyInfoService;
import org.footballmanager.pandafootball.system.service.FootSociatyService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service("footSociatyInfoService")
public class FootSociatyInfoServiceImpl extends ServiceImpl<FootSociatyInfo> implements FootSociatyInfoService {
    @Autowired
    private FootSociatyInfoMapper footSociatyInfoMapper;
    @Autowired
    private FootSociatyService footSociatyService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 根据战队主键查所有会员
     *
     * @param zdId 战队主键
     * @return 战队所有会员
     */
    @Override
    public List<FootSociatyInfo> findSociatyBySociatyId(Long zdId) {
        FootSociatyInfoSearchForm footSociatyInfoSearchForm = new FootSociatyInfoSearchForm();
        footSociatyInfoSearchForm.setZdId(zdId);
        return this.findall(footSociatyInfoSearchForm);
    }

    /**
     * 根据用户主键查单条对应关系信息
     *
     * @param userId  用户主键
     * @param request 请求
     * @return 对应关系信息
     */
    @Override
    public FootSociatyInfo findFootSociatyInfoByUserid(Long userId, HttpServletRequest request) {
        Example example = new Example(FootSociatyInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Constants.USERID, userId);
        criteria.andEqualTo("delFlag", 0);
        FootSociatyInfo fsi = this.findByExample(example);
        if (fsi != null) {
            if (!StringUtils.isEmpty(fsi.getZdId())) {
                return null;
            } else {
                return fsi;
            }
        } else {
            FootSociatyInfo fsinew = new FootSociatyInfo();
            fsinew.setUserId(userId);
            fsinew.setRelation(ZDZW.MEMBER);
            this.save(fsinew, request);
            return fsinew;
        }
    }

    /**
     * 根据用户主键删除公会信息（退出公会）
     *
     * @param userId  用户主键
     * @param request 请求
     * @return 是否成功
     */
    @Override
    public boolean exitSociaty(Long userId, HttpServletRequest request) {
        Example example = new Example(FootSociatyInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Constants.USERID, userId);
        criteria.andEqualTo("delFlag", 0);
        FootSociatyInfo fsi = this.findByExample(example);
        if (fsi != null && !StringUtils.isEmpty(fsi.getZdId())) {
            fsi.setZdId(null);
            fsi.setRelation(ZDZW.MEMBER);
            //退出战队荣誉值清零否
            fsi.setHonor(0L);
            this.updateNotNull(fsi, request);
            return footSociatyService.exitSociaty(userId, fsi.getZdId(), request);
        }
        return false;
    }

    /**
     * 翻页方法
     *
     * @param footSociatyInfoSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootSociatyInfo> findall(FootSociatyInfoSearchForm footSociatyInfoSearchForm) {
        return footSociatyInfoMapper.findall(footSociatyInfoSearchForm);
    }

    /**
     * 根据主键获取记录
     *
     * @param id 主键
     * @return 记录
     */
    @Override
    public FootSociatyInfo get(Serializable id) {
        return footSociatyInfoMapper.findById(id);
    }

    @Override
    public FootSociatyInfo getSociatyByUserId(Long userId) {
        FootSociatyInfoSearchForm footSociatyInfoSearchForm = new FootSociatyInfoSearchForm();
        footSociatyInfoSearchForm.setUserId(userId);
        List<FootSociatyInfo> list = this.findall(footSociatyInfoSearchForm);
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据战队关系主键和状态查询人员记录
     *
     * @param zdId 战队主键
     * @return 人员记录列表
     */
    @Override
    public List<FootSociatyInfo> findSociatyBySociatyIdAndAgree(Long zdId, Boolean isAgree) {
        FootSociatyInfoSearchForm footSociatyInfoSearchForm = new FootSociatyInfoSearchForm();
        footSociatyInfoSearchForm.setZdId(zdId);
        footSociatyInfoSearchForm.setAgree(isAgree);
        return this.findall(footSociatyInfoSearchForm);
    }

    /**
     * 初始化战队关联信息记录
     *
     * @param u       用户实体类
     * @param request 请求
     */
    @Override
    public void saveNewSociaty(FootUser u, HttpServletRequest request) {
        FootSociatyInfo info = new FootSociatyInfo();
        info.setAgree(false);
        info.setRelation(ZDZW.NULL);
        info.setUserId(u.getId());
        this.save(info, request);
    }

    /**
     * 同意加入战队
     *
     * @param id      主键
     * @param agree   是否同意
     * @param request 请求
     */
    @Override
    public void agree(Long id, Boolean agree, HttpServletRequest request) {
        FootSociatyInfo info = this.get(id);
        if (agree) {
            info.setAgree(true);
            info.setRelation(ZDZW.MEMBER);
            this.updateNotNull(info, request);
            //加入后战队人数增加
            FootSociaty footSociaty = footSociatyService.get(info.getZdId());
            if (footSociaty != null) {
                footSociaty.setHaveNum(footSociaty.getHaveNum() + 1);
                footSociatyService.updateNotNull(footSociaty, request);
                CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
                JSONObject obj = new JSONObject();
                obj.put("type", 2);
                obj.put(Constants.USERID, info.getUserId());
                rabbitTemplate.convertAndSend(AmqpConfig.EXCHANGE, AmqpConfig.ROUTINGKEY, obj.toString(), correlationId);
            }
        } else {
            info.setZdId(null);
            info.setAgree(false);
            this.updateNotNull(info, request);
        }
    }

    /**
     * 删除用户时删除相关信息
     *
     * @param id      用户主键
     * @param request 请求
     */
    @Override
    public void deleteByUserid(Long id, HttpServletRequest request) {
        FootSociatyInfo footSociatyInfo = this.findFootSociatyInfoByUserid(id, request);
        if (footSociatyInfo != null) {
            //删除之前把战队里的人物数量-1
            FootSociaty footSociaty = footSociatyService.get(footSociatyInfo.getZdId());
            footSociaty.setHaveNum(footSociaty.getHaveNum() - 1);
            footSociatyService.updateNotNull(footSociaty, request);
            super.delete(footSociatyInfo.getId(), request);
        }
    }

    /**
     * 查询
     *
     * @param entityname                实体类名
     * @param map                       参数
     * @param footSociatyInfoSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootSociatyInfoSearchForm footSociatyInfoSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footSociatyInfoSearchForm);
        Page<FootSociatyInfo> page = PageHelper.startPage(footSociatyInfoSearchForm.getPageIndex(), footSociatyInfoSearchForm.getPageSize());
        List<FootSociatyInfo> list = this.findall(footSociatyInfoSearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 删除所有
     *
     * @param footSociatyInfoSearchForm 条件
     * @param request                   请求
     */
    @Override
    public void deleteAll(FootSociatyInfoSearchForm footSociatyInfoSearchForm, HttpServletRequest request) {
        if (footSociatyInfoSearchForm.getSelectIds() != null) {
            String[] result = footSociatyInfoSearchForm.getSelectIds().split(Constants.COMMA);
            for (String id : result) {
                this.delete(Long.parseLong(id), request);
            }
        }
    }
}
